package com.jalarbee.core.user.dao.impl;

import java.util.List;

import javax.persistence.Query;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

import com.jalarbee.core.generic.dao.impl.GenericDaoJpa;
import com.jalarbee.core.user.business.User;
import com.jalarbee.core.user.dao.UserDao;
import com.jalarbee.core.user.dao.exception.NoSuchUserFound;
import com.jalarbee.core.user.util.Str;
import com.jalarbee.core.user.util.UserFilter;
import com.jalarbee.core.util.Chunk;

@Repository(value = "userDao")
public class UserDaoJpa extends GenericDaoJpa<User, Integer> implements UserDao {

    @SuppressWarnings("unchecked")
    @Override
    public List<User> find(UserFilter filter, Chunk chunk) throws DataAccessException {
        StringBuffer buffer = new StringBuffer();
        buffer.append("SELECT u FROM User u ");

        String whereCOndition = buildWhereCOndition(filter);

        if (!Str.isNullOrEmpty(whereCOndition)) {
            buffer.append("WHERE ");
            buffer.append(whereCOndition);
        }

        Query query = getEntityManager().createQuery(buffer.toString());

        if (chunk != null && chunk.makesSense()) {
            query.setFirstResult(chunk.getStart());
            query.setMaxResults(chunk.getSize());
        }
        return (List<User>) query.getResultList();
    }

    private String buildWhereCOndition(UserFilter filter) {
        StringBuffer buffer = new StringBuffer();

        if (!Str.isNullOrEmpty(filter.getUsername())) {
            if (buffer.length() > 0) {
                buffer.append("AND ");
            }
            buffer.append("u.credentials.username like '" + filter.getUsername() + "%' ");
        }
        if (!Str.isNullOrEmpty(filter.getLastname())) {
            if (buffer.length() > 0) {
                buffer.append("AND ");
            }
            buffer.append("u.profile.firstName like '" + filter.getName() + "%' ");
        }
        if (!Str.isNullOrEmpty(filter.getName())) {
            if (buffer.length() > 0) {
                buffer.append("AND ");
            }
            buffer.append("u.profile.lastName like '" + filter.getLastname() + "%' ");
        }
        return buffer.toString();
    }

    @Override
    public User findUserByName(String name) throws NoSuchUserFound {
        Query q = getEntityManager().createQuery("from User u where u.credentials.username=:name");
        q.setParameter("name", name);
        try {
            return (User) q.getSingleResult();
        } catch (Exception e) {
            throw new NoSuchUserFound(e);
        }
    }
}